import 'dart:typed_data';
import 'dart:io';
import 'dart:ui';

import 'package:abc/page/publish_success_page.dart';
import 'package:abc/page/video_player_page.dart';
import 'package:abc/view/MyAlertDialog.dart';
import 'package:abc/view/TopicSelectionSheet.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:video_player/video_player.dart';

// 定义帖子类型枚举
enum PostType { textImage, video }

class PublishPostController extends GetxController {
  // 状态管理
  final Rx<PostType?> selectedType = Rx<PostType?>(
    PostType.textImage,
  ); //默认选中图文帖子

  final Rx<String?> videoImgCover = Rx<String?>(null); //用于上传的视频封面

  final Rx<Uint8List?> thumbnailBytes = Rx<Uint8List?>(null); //自动生成的用于显示的视频封面

  final imagePaths = <String>[].obs; // 9张图片

  final Rx<String?> videoPath = Rx<String?>(null); //视频路径

  // 帖子标题
  RxString title = ''.obs;

  // 帖子内容
  RxString content = ''.obs;
  
  // 价格
  RxString prince = ''.obs;

  // 选中的话题
  final selectedTopics = <String>[].obs;


  @override
  void onInit() {
    super.onInit();
  }

  // 添加图片
  void addImage(String imagePath) {
    if (imagePaths.length < 9) {
      imagePaths.add(imagePath);
    }
  }

  // 移除图片
  void removeImage(int index) {
    if (index >= 0 && index < imagePaths.length) {
      imagePaths.removeAt(index);
    }
  }

  // 移除视频封面
  void removeVideoImgCover() {
    videoImgCover.value = null;
  }

  // 移除视频
  void removeVideo() {
    thumbnailBytes.value = null;
    videoPath.value = '';
  }

  // 设置视频路径
  void setVideoPath(String path) {
    videoPath.value = path;
  }

  // 清除视频
  void clearVideo() {
    videoPath.value = '';
  }

  // 设置选中的话题
  void setSelectedTopics(List<String> topics) {
    selectedTopics.value = topics;
  }

  // 发布帖子
  Future<void> publishPost() async {

    print(
      '发布帖子: 标题=$title, 内容=$content, 图片数=${imagePaths.length}, 视频=$videoPath,视频封面=$videoImgCover, 标签=$selectedTopics',
    );

   
    // 模拟网络请求
    await Future.delayed(Duration(seconds: 1));

    // 发布成功后返回上一页
   await Get.to(PublishSuccessPage());
   Get.back();
  }

  // 选择图片的方法
  Future<void> selectImages() async {
    try {
      // 请求权限
      final PermissionState permission =
          await PhotoManager.requestPermissionExtend();
      if (!permission.isAuth) {
        // 权限被拒绝
        Get.snackbar('提示', '请允许访问相册权限');
        return;
      }

      // 计算还能选择多少张图片
      final int maxSelect = 9 - imagePaths.length;

      // 使用 wechat_assets_picker 选择图片
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: AssetPickerConfig(
          maxAssets: maxSelect,
          requestType: RequestType.image,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        // 获取图片路径并添加到控制器
        for (var asset in assets) {
          final String? imagePath = await asset.originFile.then(
            (file) => file?.path,
          );
          if (imagePath != null) {
            addImage(imagePath);
          }
        }
      }
    } catch (e) {
      Get.snackbar('错误', '选择图片失败: $e');
    }
  }

  // 选择图片的方法
  Future<void> selectVideoCover() async {
    try {
      // 请求权限
      final PermissionState permission =
          await PhotoManager.requestPermissionExtend();
      if (!permission.isAuth) {
        // 权限被拒绝
        Get.snackbar('提示', '请允许访问相册权限');
        return;
      }
      // 使用 wechat_assets_picker 选择图片
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final AssetEntity asset = assets.first;
        final String? imagePath = await asset.originFile.then(
          (file) => file?.path,
        );

        videoImgCover.value = imagePath;
      }
    } catch (e) {
      Get.snackbar('错误', '选择图片失败: $e');
    }
  }

  Future<void> selectVideo() async {
    try {
      // 请求权限
      final PermissionState permission =
          await PhotoManager.requestPermissionExtend();
      if (!permission.isAuth) {
        // 权限被拒绝
        Get.snackbar('提示', '请允许访问相册权限');
        return;
      }
      print('上传视频');
      // 使用 wechat_assets_picker 选择视频
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1, // 只能选择一个视频
          requestType: RequestType.video,
        ),
      );
      print('上传视频完成');
      if (assets != null && assets.isNotEmpty) {
        final AssetEntity asset = assets.first;

        final String? videoPath = await asset.originFile.then(
          (file) => file?.path,
        );

        if (videoPath != null) {
          thumbnailBytes.value = await VideoThumbnail.thumbnailData(
            video: videoPath, // 视频文件的路径
            imageFormat: ImageFormat.JPEG,
            maxHeight: 240, // 指定封面最大高度
            quality: 100, // 封面质量 (0-100)
          );
          setVideoPath(videoPath);
        }
      }
    } catch (e) {
      Get.snackbar('错误', '选择视频失败: $e');
    }
  }

  // 播放视频的方法
  Future<void> playVideo() async {
    if (videoPath.value != null && videoPath.value!.isNotEmpty) {
      // 导航到视频播放页面
     Get.to(() => VideoPlayerPage(videoPath: videoPath.value!));
   
    } else {
      Get.snackbar('提示', '请先选择一个视频');
    }
  }

  void showTopicSelectionBottomSheet(BuildContext context, {List<String>? topics}) {
    // 如果没有传入话题列表，则使用默认的话题列表
    final List<String> topicList = topics ?? [
      '#美食',
      '#爱生活爱美食',
      '#说走就走的旅行',
      '#寻找一起吃午饭的搭子',
      '#日常穿搭',
      '#运动健身',
      '#科技数码',
      '#萌宠日常'
    ];
    
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许弹窗高度自适应
      backgroundColor: Colors.transparent, // 关键：使弹窗内容可以有圆角
      builder: (BuildContext context) {
        return TopicSelectionSheet(
          topics: topicList,
          initialSelectedTopics: selectedTopics.toList(),
        );
      },
    ).then((selectedTopics) {
      // 处理回调结果
      if (selectedTopics != null) {
        setSelectedTopics(selectedTopics);
      }
    });
  }

  void exitSure() {
    MyAlertDialog()
        .title("将退出次编辑？")
        .subTitle("您将退出此编辑，内容不会被保留是否确定此操作")
        .completeCallBack(() {
          Get.back();
          Get.back();
        })
        .cancleCallBack(() {
          Get.back();
        })
        .show();
  }
}